package pg

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/common/gensql"
	"time"
)

var _ ApiLogModel = (*customApiLogModel)(nil)

type (
	// ApiLogModel is an interface to be customized, add more methods here,
	// and implement the added methods in customApiLogModel.
	ApiLogModel interface {
		apiLogModel
		Find(ctx context.Context, uid int64, startTime, endTime *time.Time, pageNo, pageSize int64) ([]*ApiLog, error)
		Count(ctx context.Context, uid int64, startTime, endTime *time.Time) (int64, error)
	}

	customApiLogModel struct {
		*defaultApiLogModel
		logx.Logger
		genSql *gensql.GenSql
	}
)

// NewApiLogModel returns a model for the database table.
func NewApiLogModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) ApiLogModel {
	return &customApiLogModel{
		defaultApiLogModel: newApiLogModel(conn, c, opts...),
		Logger:             logx.WithDuration(time.Second),
		genSql:             gensql.NewGenSql(),
	}
}

func (m *customApiLogModel) Find(ctx context.Context, uid int64, startTime, endTime *time.Time, pageNo, pageSize int64) ([]*ApiLog, error) {
	query := fmt.Sprintf("select %s from %s ", apiLogRows, m.table)
	m.genSql.InitSql(query)
	if uid != 0 {
		m.genSql = m.genSql.Where("uid = ?", uid)
	}
	if startTime != nil {
		m.genSql = m.genSql.Where("create_time >= ?", startTime)
	}
	if endTime != nil {
		m.genSql = m.genSql.Where("create_time <= ?", endTime)
	}
	q, v, err := m.genSql.OrderBy("id desc").Limit(uint64(pageSize)).Offset(uint64((pageNo - 1) * pageSize)).ToSql()
	if err != nil {
		m.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	var list []*ApiLog
	err = m.QueryRowsNoCacheCtx(ctx, &list, q, v...)
	if err != nil {
		m.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	return list, nil
}

func (m *customApiLogModel) Count(ctx context.Context, uid int64, startTime, endTime *time.Time) (int64, error) {
	query := fmt.Sprintf("select count(id) from %s ", m.table)
	m.genSql.InitSql(query)
	if uid != 0 {
		m.genSql = m.genSql.Where("uid = ?", uid)
	}
	if startTime != nil {
		m.genSql = m.genSql.Where("create_time >= ?", startTime)
	}
	if endTime != nil {
		m.genSql = m.genSql.Where("create_time <= ?", endTime)
	}
	q, v, err := m.genSql.ToSql()
	if err != nil {
		m.Logger.Errorf("err == ", zap.Error(err))
		return 0, err
	}
	var cnt int64
	err = m.QueryRowNoCacheCtx(ctx, &cnt, q, v...)
	if err != nil {
		m.Logger.Errorf("err == ", zap.Error(err))
		return 0, err
	}
	return cnt, nil
}
